<?php defined('SYSPATH') or die('No direct script access.');

class Model_Uniapp_Images extends ORM
{
    public static function save_product_img($type_id, $product_id, $img, $uni_img_key)
    {
        if ($type_id && $product_id) {
            if (count($img) > 0) {
                $litpic = $img[$uni_img_key] ?: reset($img);
                $model  = ORM::factory('uniapp_images');
                $model->where('type_id', '=', $type_id);
                $model->and_where('product_id', '=', $product_id);
                $model->find();
                if (!$model->id) {
                    $model->type_id    = $type_id;
                    $model->product_id = $product_id;
                }
                $model->litpic  = $litpic;
                $model->piclist = implode(',', $img);
                $model->save();
            } else {
                DB::delete('uniapp_images')->where('type_id', '=', $type_id)->and_where('product_id', '=', $product_id)->execute();
            }
        }
    }

    public static function get_product_img($type_id, $product_id)
    {
        $images = DB::select()->from('uniapp_images')
            ->where('type_id', '=', $type_id)
            ->and_where('product_id', '=', $product_id)
            ->execute()->current();
        if ($images) {
            $images['piclist']     = explode(',', $images['piclist']);
            $images['uni_img_key'] = array_search($images['litpic'], $images['piclist']);
            return $images;
        } else {
            return false;
        }
    }

    public static function get_img_list($type_id, $type = 1)
    {
        $list = DB::select()->from('uniapp_images')->where('type_id', '=', $type_id)->execute()->as_array();
        if (!$list) {
            return [];
        }
        $product_id = array_column($list, 'product_id');
        if ($type == 1) {
            $litpic   = array_column($list, 'litpic');
            $img_list = array_combine($product_id, $litpic);
        } else {
            $piclist  = array_column($list, 'piclist');
            $litpic   = array_column($list, 'litpic');
            $img_list = [
                'litpic'  => array_combine($product_id, $litpic),
                'piclist' => array_combine($product_id, $piclist)
            ];
        }

        return $img_list;
    }
}